<template>
  <!-- 主任务管理 -->
  <div style="position: relative">
    <el-card style="height: calc(100vh - 85px); overflow: auto">
      <!-- 信息搜索框 -->
      <el-form v-model="queryObj" label-width="100px" size="large">
        <el-row>
          <el-col :span="7" style="margin-right: 15px">
            <el-form-item label="容器编号：">
              <el-input v-model.trim="queryObj.unitId" placeholder="请输入容器编号" />
            </el-form-item>
          </el-col>
          <el-col :span="7" style="margin-right: 15px">
            <el-form-item label="主任务类型：">
              <el-select v-model="queryObj.mainTaskType" style="width: 100%" placeholder="请选择主任务类型">
                <el-option v-for="item in queryObj.mainTaskType" :key="item" :value="item">{{ item }}</el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-show="isopen" :span="7" style="margin-right: 15px">
            <el-form-item label="任务编号：">
              <el-input v-model.trim="queryObj.taskId" placeholder="请输入任务编号" />
            </el-form-item>
          </el-col>
          <el-col v-show="isopen" :span="7" style="margin-right: 15px">
            <el-form-item label="发送者：">
              <el-input v-model.trim="queryObj.sender" placeholder="请输入发送者" />
            </el-form-item>
          </el-col>
          <el-col v-show="isopen" :span="7" style="margin-right: 15px">
            <el-form-item label="优先级：">
              <el-input v-model.trim="queryObj.priority" placeholder="请输入优先级" />
            </el-form-item>
          </el-col>
          <el-col v-show="isopen" :span="7" style="margin-right: 15px">
            <el-form-item label="起始点：">
              <el-input v-model.trim="queryObj.fromLoc" placeholder="请输入起始点" />
            </el-form-item>
          </el-col>
          <el-col v-show="isopen" :span="7" style="margin-right: 15px">
            <el-form-item label="目的点：">
              <el-input v-model.trim="queryObj.toLoc" placeholder="请输入目的点" />
            </el-form-item>
          </el-col>

          <el-col v-show="isopen" :span="7" style="margin-right: 15px">
            <el-form-item label="时间：">
              <el-date-picker
              v-model="timestart_end" 
              style="width:100%" 
              type="datetimerange" 
              start-placeholder="开始日期" 
              end-placeholder="结束日期" 
              format="yyyy/MM/dd HH:mm:ss"
              value-format="yyyy/MM/dd HH:mm:ss" 
              @change="handleDataChanged" range-separator="至" :default-time="['00:00:00', '23:59:59']" />
            </el-form-item>
          </el-col>
          <searchbutton :isopen="isopen" @isopenclickfn="isopenclick" @resetQueryfn="resetQuery" @queryClickfn="queryClick" />
        </el-row>
      </el-form>

      <!-- 调整状态按钮 -->
      <el-row style="margin-bottom: 10px">
        <div style="float: left">
          <!-- <el-button v-permission="'main-task-create'" type="primary" class="custom-btn btn-3" @click="centerDialogVisible = true"><i class="el-icon-plus" /> 创建任务</el-button> -->
          <el-button v-permission="'main-task-create'" type="primary" plain @click="centerDialogClick"><i class="el-icon-plus" /> 创建任务</el-button>
          <!-- <el-button type="danger" plain @click="allDelete"><i class="el-icon-delete" /> 批量删除</el-button> -->
        </div>
        <!-- 右侧公用按钮功能 -->
        <div style="float: right">
          <div style="font-size: 30px; display: inline-block; margin-right: 5px">
            <a href="#">
              <el-tooltip class="item" effect="dark" content="列位置" placement="top" style="cursor: pointer">
                <el-dropdown trigger="click" :hide-on-click="false">
                  <span class="el-dropdown-link">
                    <i class="el-icon-s-grid el-icon--right" style="font-size: 24px; color: black" />
                  </span>
                  <el-dropdown-menu slot="dropdown" style="width: 190px; height: 300px; overflow: auto">
                    <el-dropdown-item><el-checkbox v-model="deleteCell.istaskId">任务编号</el-checkbox></el-dropdown-item>
                    <el-dropdown-item><el-checkbox v-model="deleteCell.issender">sender</el-checkbox></el-dropdown-item>
                    <el-dropdown-item><el-checkbox v-model="deleteCell.ismainTaskType">主任务类型</el-checkbox></el-dropdown-item>
                    <el-dropdown-item><el-checkbox v-model="deleteCell.isunitId">容器编号</el-checkbox></el-dropdown-item>
                    <el-dropdown-item><el-checkbox v-model="deleteCell.isfromLoc">起始点</el-checkbox></el-dropdown-item>
                    <el-dropdown-item><el-checkbox v-model="deleteCell.istoLoc">目的点</el-checkbox></el-dropdown-item>
                    <el-dropdown-item><el-checkbox v-model="deleteCell.istaskStatus">任务状态</el-checkbox></el-dropdown-item>
                    <el-dropdown-item><el-checkbox v-model="deleteCell.isactiveSubTaskId">当前子任务</el-checkbox></el-dropdown-item>
                    <el-dropdown-item><el-checkbox v-model="deleteCell.istotalSubTaskNum">子任务总数</el-checkbox></el-dropdown-item>
                    <el-dropdown-item><el-checkbox v-model="deleteCell.isextend">extend</el-checkbox></el-dropdown-item>
                    <el-dropdown-item><el-checkbox v-model="deleteCell.isreasonCode">reasonCode</el-checkbox></el-dropdown-item>
                    <el-dropdown-item><el-checkbox v-model="deleteCell.ispriority">任务优先级</el-checkbox></el-dropdown-item>
                    <el-dropdown-item><el-checkbox v-model="deleteCell.iscreatedTime">创建时间</el-checkbox></el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </el-tooltip>
            </a>
          </div>
          <!-- 右侧公用按钮功能组件 -->
          <functionButton style="float:right" :refresh-click="refreshClick" :table-data="tableData" :table-data-all="tableDataAll" :headers-arr="headersArr" :headers-relations="headersRelations"
            @exportAllfn="exportAll" />
        </div>
      </el-row>
      <!-- 任务总表 -->
      <el-table v-if="tableData.taskId !== ''" ref="mainTable" v-loading="listLoading" :selection-change="handletableSelect" :data="tableData" border :row-style="{ height: '40px' }"
        :cell-style="{ padding: '0px' }" style="width: 100%; margin-bottom: 10px; overflow: auto">
        <el-table-column fixed="left" width="90" align="center">
          <template slot-scope="scopedata">
            <!-- <el-button type="text" size="small" @click.native="handleUpdate(scopedata.row)">完成</el-button> -->
            <el-button v-permission="'main-task-delete'" type="text" size="small" @click="allDelete(scopedata.row)"><i class="el-icon-delete" style="color: red; font-size: 16px" /></el-button>
            <!-- <el-button v-permission="'main-task-delete'" type="text" size="small">优先级-未完成</el-button> -->
          </template>
        </el-table-column>
        <!-- 子任务下拉表格 -->
        <el-table-column type="expand" fixed="left">
          <template slot-scope="scope">
            <!-- {{ scope.$index }} - {{ scope.row }} -->
            <!-- {{ scope.row.subTasks }} -->
            <el-table style="margin-left: -23px" :data="scope.row.subTasks" border :row-style="{ height: '40px' }" :cell-style="{ padding: '0px' }">
              <el-table-column prop="taskSeq" label="序号" align="center" width="50" />
              <el-table-column prop="taskFrom" label="任务来源" width="120" />
              <el-table-column prop="subTaskId" label="子任务编号" width="150" />
              <el-table-column prop="subTaskType" label="子任务类型" width="180" />
              <el-table-column prop="unitId" label="容器编号" width="180" />
              <el-table-column prop="fromLoc" label="起始点" width="180" />
              <el-table-column prop="toLoc" label="目的点" width="180" />
              <el-table-column prop="taskStatus" label="任务状态" width="180" />
              <el-table-column prop="plcName" label="plc名" width="180" />
              <el-table-column fixed="left" align="center" width="80">
                <template slot-scope="scopedata">
                  <el-tooltip class="item" effect="dark" content="完成" placement="top">
                    <el-button v-permission="'main-task-finish'" type="text" size="small" @click.native="handleUpdate(scopedata.row)"><i class="el-icon-check"
                        style="font-size: 20px; color: #67c23a" /></el-button>
                  </el-tooltip>
                  <el-tooltip class="item" effect="dark" content="重置" placement="top">
                    <el-button v-permission="'main-task-reset'" type="text" size="small" @click.native="handleReset(scopedata.row)"><i class="el-icon-refresh" style="font-size: 20px" /></el-button>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>

        <el-table-column v-if="deleteCell.istaskId" prop="taskId" label="任务编号" width="180" show-overflow-tooltip>
          <template slot-scope="scope">
            <!-- :data-clipboard-text 复制的内容 -->
            <span class="copydemo" :data-clipboard-text="scope.row.taskId" @click="copy">{{ scope.row.taskId }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="deleteCell.issender" prop="sender" label="sender" width="100" />
        <el-table-column v-if="deleteCell.ismainTaskType" prop="mainTaskType" label="主任务类型" width="160" />
        <el-table-column v-if="deleteCell.isunitId" prop="unitId" label="容器编号" width="160" />
        <el-table-column v-if="deleteCell.ispriority" prop="priority" label="任务优先级" width="110">
          <template slot-scope="scope">
            <el-button type="text" @click="priorityClick(scope.row)">{{ scope.row.priority }}</el-button>
          </template>
        </el-table-column>
        <el-table-column v-if="deleteCell.isfromLoc" prop="fromLoc" label="起始点" width="160" />
        <el-table-column v-if="deleteCell.istoLoc" prop="toLoc" label="目的点" width="160" />
        <el-table-column v-if="deleteCell.istaskStatus" prop="taskStatus" label="任务状态" width="100" />
        <el-table-column v-if="deleteCell.isactiveSubTaskId" prop="activeSubTaskId" label="当前子任务" width="110" />
        <el-table-column v-if="deleteCell.istotalSubTaskNum" prop="totalSubTaskNum" label="子任务总数" width="110" />
        <el-table-column v-if="deleteCell.isextend" prop="extend" label="extend" width="160" />
        <el-table-column v-if="deleteCell.isreasonCode" prop="reasonCode" label="reasonCode" width="160" />
        <el-table-column v-if="deleteCell.iscreatedTime" prop="createdTime" label="创建时间" width="160" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ scope.row.createdTime | formatDate }}</span>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <paging :pagion-obj="pagionObj" :handle-size-change="handleSizeChange" :handle-page-change="handlePageChange" />

      <!-- 创建任务弹窗 -->
      <maintaskCreateTask :center-dialog-visible="centerDialogVisible" :Machines="Machines" :LocationCascader="LocationCascader" @handleClosefn="handleClose" @createMainTaskfn="createMainTask" />
    </el-card>
    <!-- 修改优先级弹窗 -->
    <el-dialog :visible.sync="priorityDialog" width="500px">
      <el-form ref="priorityRef" :model="priorityData" size="mini" @keyup.native.enter="priorityConfirm" label-width="100px">
        <el-form-item label="主任务类型：">
          <span>{{priorityData.priorityTitle}}</span>
        </el-form-item>
        <el-form-item label="当前优先级：">
          <span>{{priorityData.nowPriority}}</span>
        </el-form-item>
        <el-form-item label="优先级：">
          <!-- <el-select v-model="priorityData.priority" style="width: 50%" placeholder="请选择优先级">
            <el-option value="1" :label="1"></el-option>
            <el-option value="2" :label="2"></el-option>
            <el-option value="3" :label="3"></el-option>
            <el-option value="4" :label="4"></el-option>
            <el-option value="5" :label="5"></el-option>
          </el-select> -->
          <el-input style="width:60%;" v-model.trim="priorityData.priority" placeholder="请输入优先级"></el-input>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="priorityTop">置 顶</el-button>
        <el-button type="primary" @click="priorityConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getmaintaskdataapi,
  deleteMaintaskApi,
  updateSubDateApi,
  ChangeMainTaskPriorityapi,
  GetMachinesapi,
  GetLocationCascaderapi,
} from "@/api/task";
import { Message } from "element-ui";
import permission from "@/permission/index.js"; // 权限判断指令
import maintaskCreateTask from "./components/main-task-createTask.vue";
import { copyData } from "@/utils/index";
export default {
  name: "MainTaskPage",
  directives: { permission },
  components: {
    maintaskCreateTask,
  },
  data() {
    return {
      queryObj: {
        sender: "", // 发送者
        taskId: "", // 任务编号
        fromLoc: "", // 起始点
        toLoc: "", // 目的点
        unitId: "", // 容器编号
        priority: "", // 优先级
        extend: "", //
        reasonCode: "", //
        mainTaskType: "", // 当前子任务
        activeSubTaskId: "", // 子任务总数totalSubTaskNum
        totalSubTaskNum: "", //
        taskStatus: "", //
        page: 0, // 第几页
        size: 0, // 每页条数
        startTime: "0001/1/1 0:00:00", // 开始日期
        endTime: "0001/1/1 0:00:00", // 结束日期
      },
      // 分页页码数据
      pagionObj: {
        size: 10,
        currentPage: 1,
        total: 100,
      },
      // 请求返回的数据
      tableData: [],
      tableDataAll: [],
      // 时间的数据
      timestart_end: [],
      // 创建任务dialog显示隐藏
      centerDialogVisible: false,
      // fromitem是否显示
      isopen: false,
      // loding效果显示
      listLoading: true,
      //修改优先级弹窗
      priorityDialog: false,
      priorityData: {
        id: "",
        priority: "",
        priorityTitle: "",
        nowPriority: "",
        unitId: "",
      },
      //设备列表
      Machines: [],
      //级联货架列表
      LocationCascader: [],
      // 列位置 数据
      deleteCell: {
        istaskId: true,
        issender: true,
        ismainTaskType: true,
        isunitId: true,
        isfromLoc: true,
        istoLoc: true,
        istaskStatus: true,
        isactiveSubTaskId: true,
        istotalSubTaskNum: true,
        isextend: true,
        isreasonCode: true,
        ispriority: true,
        iscreatedTime: true,
      },
      // excel 数据的key 表头数据
      headersArr: [
        "id",
        "sender",
        "任务编号",
        "起始点",
        "目的点",
        "容器编号",
        "任务优先级",
        "extend",
        "reasonCode",
        "主任务类型",
        "当前子任务",
        "子任务总数务",
        "创建时间",
        "任务状态",
        // '子任务'
      ],
      // 将表头转换成中文
      headersRelations: {
        id: "id",
        sender: "sender",
        任务编号: "taskId",
        起始点: "fromLoc",
        目的点: "toLoc",
        容器编号: "unitId",
        任务优先级: "priority",
        extend: "extend",
        reasonCode: "reasonCode",
        主任务类型: "mainTaskType",
        当前子任务: "activeSubTaskId",
        子任务总数务: "totalSubTaskNum",
        创建时间: "createdTime",
        任务状态: "taskStatus",
        // '子任务': 'subTasks'
      },
    };
  },
  // 监听时间的变化
  watch: {
    timestart_end(newData) {
      if (newData !== null && newData.length > 0) {
        this.queryObj.startTime = this.timestart_end[0];
        this.queryObj.endTime = this.timestart_end[1];
      } else {
        this.queryObj.startTime = "0001/1/1 0:00:00";
        this.queryObj.endTime = "0001/1/1 0:00:00";
      }
    },
  },
  mounted() {
    this.queryData();
    // console.log(this.$route.meta.title, 111)
  },
  methods: {
    /** 获取页面数据*/
    async queryData() {
      this.listLoading = true;
      this.queryObj.size = this.pagionObj.size;
      this.queryObj.page = this.pagionObj.currentPage;
      const res = await getmaintaskdataapi(this.queryObj);
      this.tableData = res.data.data;
      this.pagionObj.pageCount = res.data.pageCount;
      this.pagionObj.total = res.data.count;
      this.listLoading = false;
    },
    // 搜索按钮
    queryClick() {
      this.pagionObj.currentPage = 1;
      this.queryData();
    },
    // 刷新按钮
    refreshClick() {
      this.listLoading = true;
      this.queryData();
      this.listLoading = false;
    },
    /** 每页显示数据变化*/
    handleSizeChange(val) {
      this.pagionObj.size = val;
      this.queryData();
    },
    /** 当前页变化*/
    handlePageChange(val) {
      this.pagionObj.currentPage = val;
      this.queryData();
    },
    // 时间选择器处理
    handleDataChanged() {
      if (this.timestart_end !== null) {
        this.queryObj.startTime = this.timestart_end[0];
        this.queryObj.endTime = this.timestart_end[1];
      } else {
        this.queryObj.startTime = "0001/1/1 0:00:00";
        this.queryObj.endTime = "0001/1/1 0:00:00";
      }
    },
    // 重置按钮
    resetQuery() {
      this.queryObj.unitId = "";
      this.queryObj.mainTaskType = "";
      this.queryObj.sender = "";
      this.queryObj.taskId = "";
      this.queryObj.priority = "";
      this.queryObj.fromLoc = "";
      this.queryObj.toLoc = "";
      this.queryObj.extend = "";
      this.queryObj.reasonCode = "";
      this.timestart_end = [];
    },
    //打开创建任务dialog
    centerDialogClick() {
      this.centerDialogVisible = true;
      this.GetMachines();
    },
    // 关闭创建任务dialog
    handleClose() {
      this.centerDialogVisible = false;
      // this.createTask.taskType = ''
    },
    // 表达校验确认创建任务
    async createMainTask() {
      this.queryData();
    },
    //
    handletableSelect(selection) {
      console.log(selection);
    },
    // 批量删除
    async allDelete(data) {
      console.log(data.id, "data");
      // 获取表格被选中的数据
      // console.log(this.$refs.mainTable.selection)
      // const numid = this.$refs.mainTable.selection.map(item => item.id)
      // console.log(numid)
      // if (!numid.length > 0) return
      // console.log(numid, '删除的id')
      this.$confirm("确认删除该任务吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          // console.log('确认')
          await deleteMaintaskApi(data.id);
          Message.success("删除成功");
          this.queryData();
          setTimeout(() => {
            this.queryData();
          }, 1000);
        })
        .catch(() => {
          // console.log('取消')
        });
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 更新子任务状态
    async handleUpdate(data) {
      this.$confirm("确认完成该任务吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await updateSubDateApi({ taskId: data.id, taskStatus: 3 });
          Message.success("操作成功");
          this.queryData();
        })
        .catch(() => {});
    },
    // 重置
    async handleReset(data) {
      this.$confirm("确认重置该任务吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await updateSubDateApi({ taskId: data.id, taskStatus: 1 });
          Message.success("重置成功");
          this.queryData();
        })
        .catch(() => {});
    },
    // 展开收起
    isopenclick() {
      this.isopen = !this.isopen;
    },
    // 复制
    copy() {
      copyData();
    },
    //修改优先级
    priorityClick(data) {
      this.priorityData.priority = "";
      this.priorityDialog = true;
      console.log(data);
      this.priorityData.id = data.id;
      this.priorityData.priorityTitle = data.taskId;
      this.priorityData.nowPriority = data.priority;
      this.priorityData.unitId = data.unitId;
    },
    //修改优先级确认
    async priorityConfirm() {
      console.log(this.priorityData, "this.priorityData");
      const res = await ChangeMainTaskPriorityapi({
        id: this.priorityData.id,
        priority: this.priorityData.priority,
        unitId: this.priorityData.unitId,
      });
      console.log(res);
      // Message.success("操作成功");
      this.queryData();
    },
    //修改优先级置顶
    async priorityTop() {
      const res = await ChangeMainTaskPriorityapi({
        id: this.priorityData.id,
        priority: "100",
      });
      console.log(res);
      // Message.success("操作成功");
      this.queryData();
    },
    // 获取设备列表和级联货架列表
    async GetMachines() {
      const res = await GetMachinesapi();
      this.Machines = res.data.data;
      const LocationCascaderdata = await GetLocationCascaderapi();
      this.LocationCascader = LocationCascaderdata.data.data;
      console.log(this.LocationCascader);
    },
    // excel导出全部
    async exportAll() {
      const res2 = await getmaintaskdataapi({ size: 10000 });
      this.tableDataAll = res2.data.data;
    },
  },
};
</script>
<style lang="scss" scoped>
</style>
